using CMS.Application.common.Interface;
using CMS.Application.Common.Interface;
using CMS.Application.RequestDto;
using CMS.Application.ResponseDto;
using CMS.Application.Utils;
using CMS.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SoftDemo.Api.Controllers;

namespace CMS.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]

    public class TokenController : ControllerBase
    {
        private readonly IRepository<Users> _Users;
        private readonly IIdentityService _IdentityService;
        private readonly IFileUploadService _fileUploadService;

        public TokenController(IIdentityService IdentityService, IRepository<Users> Users, IFileUploadService fileUploadService)
        {
            _IdentityService = IdentityService;
            _fileUploadService = fileUploadService;
            _Users = Users;
        }

        [HttpPost("/userlogin")]
        public async Task<object> UsersLogin(UserLoginDto userLoginDto)
        {

            var user = _Users.Table.FirstOrDefault(x => (x.UserName == userLoginDto.UserName || x.Email == userLoginDto.Email) && x.PassWord == userLoginDto.PassWord);
            var UploadControllers = new UploadController(_fileUploadService);

            if (user != null)
            {
                var userForAuth = new UserForAuthDto();
                userForAuth.Username = user.UserName;
                userForAuth.Password = user.PassWord;
                var token = await _IdentityService.ValidateUserAsync(userForAuth);



                //获取头像
                var result = await UploadControllers.GetFile(user.AvatarId);
                var obj = new
                {
                    UseId = user.Id,
                    UserName = user.UserName,
                    email = user.Email,
                    result.FileContents,
                    result.ContentType,
                };
                return new
                {
                    token = token,
                    code = 200,
                    msg = "登录成功",
                    data = obj
                };
            }
            else
            {
                return new
                {
                    code = 400,
                    msg = "登录失败",
                    data = ""
                };
            }

        }

        [AllowAnonymous]
        [HttpPost("/token")]
        public async Task<string> ValidateUser(UserForAuthDto userForAuth)
        {
            var token = await _IdentityService.ValidateUserAsync(userForAuth);

            return token.SerializeObject();//JsonHelp的方法
        }


        [AllowAnonymous]
        [HttpPost("/refresh")]

        public async Task<string> RefreshToken(AppTokenDto appToken)
        {
            var token = await _IdentityService.RefreshTokenAsync(appToken);

            return token.SerializeObject();//JsonHelp的方法
        }
    }
}